import {defineComponent, PropType, useAttrs} from "vue";
import {MenuItem} from "./types";
import Icon from '../../icon/src/index.vue'
import '../../../styles/menu.scss'

export default defineComponent({
    props: {
        data: {
            type: Array as PropType<MenuItem[]>,
            required: true
        },
        defaultActive: {
            type: String,
            default: ''
        },
        router: {
            type: Boolean,
            default: false
        }
    },
    setup(props, context) {
        let renderMenu = (data: MenuItem[]) => {
            return data.map((item: MenuItem) => {
                // 插槽本质是一个函数
                let slots = {
                    title: () => {
                        return (
                            <>
                                <Icon name={item.icon}></Icon>
                                <span>{item.name}</span>
                            </>
                        )
                    }
                }
                // 包含子菜单递归调用
                if (item.children && item.children.length) {
                    return (
                        <el-sub-menu index={item.index} v-slots={slots}>
                            {renderMenu(item.children)}
                        </el-sub-menu>
                    )
                }
                // 不包含子菜单
                return (
                    <el-menu-item index={item.index}>
                        <Icon name={item.icon}></Icon>
                        <span>{item.name}</span>
                    </el-menu-item>
                )
            })
        }

        let attrs = useAttrs()

        return () => {
            return (
                <el-menu
                    default-active={props.defaultActive}
                    router={props.router}
                    {...attrs}
                >
                    {renderMenu(props.data)}
                </el-menu>
            )
        }
    }
})